import { ref, onUnmounted } from 'vue';
import { eventBus } from '../utils/eventBus';
import { videoProcessor } from '../utils/videoProcessor';

export function usePreviewPlayback(options) {
  const isPreviewPlaying = ref(false);
  const previewFrames = ref([]);
  const currentPreviewFrameIndex = ref(0);
  const previewImageUrl = ref(null);
  
  // 处理预览播放
  const startPreviewPlay = async () => {
    // Destructure options to avoid undefined errors
    const { 
      videoFile, 
      sourceVideo, 
      canvas, 
      ctx, 
      cropParams, 
      startTime, 
      endTime, 
      enableTransparency, 
      targetColor, 
      colorThreshold, 
      statusMessage, 
      initCanvas 
    } = options;
    
    if (!videoFile?.value || !sourceVideo?.value) {
      alert('请先选择视频文件');
      return;
    }
    
    statusMessage.value = "正在生成预览序列...";
    isPreviewPlaying.value = true;
    previewFrames.value = [];
    currentPreviewFrameIndex.value = 0;
    
    // 初始化画布
    if (!canvas.value) {
      initCanvas();
    }
    
    // 生成预览帧序列
    try {
      // 保存当前视频时间
      const originalTime = sourceVideo.value.currentTime;
      
      // 计算预览帧的时间间隔
      const previewStartTime = startTime?.value || 0;
      const previewEndTime = endTime?.value > 0 ? endTime.value : sourceVideo.value.duration;
      const duration = previewEndTime - previewStartTime;
      
      // 最多生成30帧预览
      const frameCount = Math.min(30, Math.floor(duration * 5)); // 每秒5帧
      const timeStep = duration / frameCount;
      
      // 生成预览帧
      for (let i = 0; i < frameCount; i++) {
        const frameTime = previewStartTime + i * timeStep;
        sourceVideo.value.currentTime = frameTime;
        
        // 等待视频跳转到指定时间
        await new Promise(resolve => {
          const seekHandler = () => {
            sourceVideo.value.removeEventListener('seeked', seekHandler);
            resolve();
          };
          sourceVideo.value.addEventListener('seeked', seekHandler);
        });
        
        // 处理当前帧
        videoProcessor.processCurrentFrame({
          video: sourceVideo.value,
          canvas: canvas.value,
          ctx: ctx.value,
          cropParams: cropParams.value,
          enableTransparency: enableTransparency.value,
          targetColor: targetColor.value,
          threshold: colorThreshold.value
        });
        
        // 保存预览帧
        previewFrames.value.push(canvas.value.toDataURL('image/png'));
        statusMessage.value = `正在生成预览序列... ${Math.round((i + 1) / frameCount * 100)}%`;
      }
      
      // 恢复原始视频时间
      sourceVideo.value.currentTime = originalTime;
      
      // 开始播放预览
      if (previewFrames.value.length > 0) {
        playNextPreviewFrame();
        statusMessage.value = `预览播放中 (${previewFrames.value.length}帧)`;
      } else {
        stopPreviewPlay();
        statusMessage.value = "无法生成预览序列";
      }
    } catch (error) {
      console.error('生成预览序列失败:', error);
      stopPreviewPlay();
      statusMessage.value = "生成预览序列失败";
    }
  };
  
  // 停止预览播放
  const stopPreviewPlay = () => {
    isPreviewPlaying.value = false;
    options.statusMessage.value = "预览播放已停止";
  };
  
  // 播放下一帧预览
  const playNextPreviewFrame = () => {
    if (!isPreviewPlaying.value || previewFrames.value.length === 0) return;
    
    // 更新预览图片
    previewImageUrl.value = previewFrames.value[currentPreviewFrameIndex.value];
    
    // 更新索引
    currentPreviewFrameIndex.value = (currentPreviewFrameIndex.value + 1) % previewFrames.value.length;
  };

  // 注册事件监听
  eventBus.on('start-preview-play', startPreviewPlay);
  eventBus.on('stop-preview-play', stopPreviewPlay);
  eventBus.on('preview-next-frame', playNextPreviewFrame);

  // 组件卸载时清理事件监听
  onUnmounted(() => {
    eventBus.off('start-preview-play');
    eventBus.off('stop-preview-play');
    eventBus.off('preview-next-frame');
    isPreviewPlaying.value = false;
  });

  return {
    isPreviewPlaying,
    previewFrames,
    currentPreviewFrameIndex,
    previewImageUrl,
    startPreviewPlay,
    stopPreviewPlay,
    playNextPreviewFrame
  };
}